package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmLoginDto;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.service.WmUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult login(WmLoginDto dto) {
        //1.进行判空操作，后台系统不允许游客登录
        if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }

        //2.根据用户名查询用户是否存在
        QueryWrapper<WmUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(WmUser::getName,dto.getName());
        WmUser wmUser=wmUserMapper.selectOne(queryWrapper);

        //3.对比密码
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"账号不存在");
        }

        String salt = wmUser.getSalt();
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        String md5Password = wmUser.getPassword();
        if(md5Password.equals(wmUser.getPassword())){
            //登录成功，返回token
            String token= AppJwtUtil.getToken(wmUser.getId().longValue());
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            wmUser.setPassword("");
            wmUser.setSalt("");
            map.put("user",wmUser);

            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
    }
}
